package com.zh.core.interceptor;

import com.zh.core.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by zhaohui on 2019/8/4
 * Description:
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        // 获取请求的URL
        String url = httpServletRequest.getRequestURI();
        System.out.println(url);
        //URL:除了登陆请求外,其它的URL都进行拦截控制
        if (url.contains("login") || url.contains("register")) {
            return true;
        }
        // 获取Session
        HttpSession session = httpServletRequest.getSession();
        User user = (User) session.getAttribute("USER_SESSION");
        // 判断Session中是否有用户数据,如果有,返回True,继续向下执行
        if (user != null) {
            return true;
        }
        // 不符合条件的给出提示信息,并转发到登陆页面
        httpServletRequest.setAttribute("msg", "您还没登陆,请先登陆");
        httpServletRequest.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(httpServletRequest, httpServletResponse);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
